package com.wechat.api.util;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * XML数据解析
 * Created by Liumh on 2018/4/11.
 */
public class XMLParser {

    public static Map<String, Object> dom4jParser(HttpServletRequest request){
        SAXReader saxReader = new SAXReader();
        Map<String, Object> result = new HashMap<String, Object>();
        try{
            InputStream inputStream = request.getInputStream();
            Document document = saxReader.read(inputStream);
            //获取xml艮元素
            Element rootElement = document.getRootElement();
            //得到根元素的所有节点
            Iterator iterator = rootElement.elementIterator();
            while (iterator.hasNext()){
                Element element = (Element) iterator.next();
                result.put(element.getName(),element.getText());
                System.out.println(element.getName()+":"+element.getText());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /*public static void main(String[] args){
        XMLParser XMLParser = new XMLParser();
        XMLParser.dom4jParser("<xml>  <ToUserName>< ![CDATA[toUser] ]></ToUserName>  <FromUserName>< ![CDATA[fromUser] ]></FromUserName>  <CreateTime>1348831860</CreateTime>  <MsgType>< ![CDATA[text] ]></MsgType>  <Content>< ![CDATA[this is a test] ]></Content>  <MsgId>1234567890123456</MsgId>  </xml>");
    }*/
}
